<?php
/**
 * XGPHP 轻量级PHP框架
 * @link http://xgphp.xg3.cn
 * @version 2.0.0
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @author 讯高科技 <xungaokeji@qq.com>
*/
namespace xg;
use \xg\facade\Cookie;
use \xg\facade\Config;
use \helper\Str;
use \helper\Arr;

class Response {
	protected $code = 200;
	protected $charset = 'UTF-8';
	protected $headers = [];
	protected $content = '';
	protected $mimes = null;

	public function __construct($content = null) {
		$this->content = $content;
	}

	public function code($code) {
		$this->code = $code;
		return $this;
	}

	public function charset(string $charset) {
		$this->charset = $charset;
		return $this;
	}

	public function header(string $name, string $value) {
		$this->headers[$name] = $value;
		return $this;
	}

	public function headers(array $headers) {
		$this->headers = Arr::extend($this->headers, $headers);
		return $this;
	}

	public function content($content) {
		$this->content = $content;
		return $this;
	}

	public function getContent() {
		return $this->content;
	}

	public function contentType(string $type) {
		$this->header('Content-Type', $type);
		return $this;
	}

	public function cacheControl(int $seconds) {
		$this->header('Cache-Control', "max-age={$seconds}");
		return $this;
	}

	public function mime(string $type) {
		if($type=='html') {
			return $this->contentType("text/html;charset={$this->charset}");
		}
		if(is_null($this->mimes)) {
			$types = Config::get('mimes');
			$this->mimes = $types;
		}
		if($types[$type]) {
			$type = $types[$type];
		}
		$this->contentType($type);
		return $this;
	}

	// 向客户端输出内容
	public function send() {
		$content = $this->output($this->content);
		if (!headers_sent()) {
			// 发送状态码
			http_response_code($this->code);
			// 发送头信息
			foreach ($this->headers as $name => $value) {
				header("$name: $value");
			}
			Cookie::save();
		}
		$_content = Hook::create('response.send-content')->run($content)->last();
		if($_content) {
			$content=$_content;
		}
		if (is_array($content)) {
			$content = json_encode($content);
		}
		echo $content;
	}

	public function done() {
		$this->send();
		exit;
	}
	
	protected function output() {
		if (is_array($this->content)) {
			return json_encode($this->content);
		}
		return $this->content;
	}

	public static function drive($type='result') {
		$class = '\\xg\\response\\'.Str::studly($type);
		if(!class_exists($class)) {
			$class = '\\xg\\response\\Result';
		}
		return new $class();
	}
}
?>